package de.kalinasch.pa.placereminder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.Toast;
import de.kalinasch.pa.placereminder.database.IncidentDataSource;
import de.kalinasch.pa.placereminder.dmo.IncidentDMO;
import de.kalinasch.pa.placereminder.util.InputValidator;

/**
 * This class displays a form were the user can enter the data for a reminder.
 * If the user data is valid a new reminder will be created and saved.
 * 
 * @author dkalinasch
 */
public class CreateReminderActivity extends Activity implements OnClickListener {
	IncidentDataSource incidentDataSource;

	/**
	 * 
	 */
	public void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);

		// Datenbankverbindung laden
		incidentDataSource = new IncidentDataSource(this);
		setContentView(R.layout.createreminder);

		// ActionListener zuordnen
		Button speichern = (Button) findViewById(R.id.button_save_create);
		speichern.setOnClickListener(this);
		TableRow gallery = (TableRow) findViewById(R.id.open_gallery);
		gallery.setOnClickListener(this);

		// Auswahlbox für Umkreis der Erinnerungsauslösung
		Spinner s1 = (Spinner) findViewById(R.id.radius);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.radien, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s1.setAdapter(adapter);
	}

	/**
	 * Method responds to the click of a button within the activity.
	 * 
	 * @param _view
	 */
	@Override
	public void onClick(View _view) {
		if (_view.getId() == R.id.button_save_create) {
			IncidentDMO incident = readIncidentData();
			if (incident == null) {
				return;
			}
			incidentDataSource.saveIncident(incident);
			Intent intent = new Intent(this, ListReminderActivity.class);
			startActivity(intent);
		}
		if(_view.getId() == R.id.open_gallery) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
		}
		
	}

	/**
	 * Reads the user input from the form to create an IncidentDMO.
	 * 
	 * @return IncidentDMO with the data specified by the user
	 */
	private IncidentDMO readIncidentData() {
		ArrayList<EditText> inputToValidate = new ArrayList<EditText>();
		EditText street = (EditText) findViewById(R.id.edit_street);
		inputToValidate.add(street);
		EditText town = (EditText) findViewById(R.id.edit_town);
		inputToValidate.add(town);
		EditText title = (EditText) findViewById(R.id.edit_reminderTitle);
		inputToValidate.add(title);
		EditText description = (EditText) findViewById(R.id.edit_description);
		inputToValidate.add(description);
		Spinner radius = (Spinner) findViewById(R.id.radius);

		if (!InputValidator.checkEditTextInput(inputToValidate)) {
			return null;
		}

		// Aus Umkreis-String int-Variable erzeugen
		String umkreis = (String) radius.getSelectedItem();
		int laenge = umkreis.length();
		umkreis = umkreis.substring(0, (laenge - 1));
		Log.d("RADIUS", "radius = " + umkreis);
		int rad = Integer.parseInt(umkreis);

		// Adresse in GPS-Daten umwandeln
		try {
			double[] gpsdata = geocoding(street.getText().toString(), town
					.getText().toString());

			// Erinnerung in Datenbank eintragen
			IncidentDMO incident = new IncidentDMO(street.getText().toString(),
					town.getText().toString(), title.getText().toString(),
					description.getText().toString(), rad, gpsdata[0],
					gpsdata[1]);
			return incident;
		} catch (Exception e) {
			return null;
		}
	}
	

	/**
	 * This method retrieves the longitude and latitude for the entered
	 * town/postcode and street.
	 * 
	 * @param _street
	 * @param _town
	 * @return
	 * @throws Exception
	 */
	private double[] geocoding(String _street, String _town) throws Exception {
		// TODO Adresse um Postleitzahl erweitern
		double lat = 0d;
		double lon = 0d;
		Geocoder geocode = new Geocoder(getApplicationContext(), Locale.getDefault());
		String location = _street + " " + _town;

		try {
			List<Address> gpsdaten = geocode.getFromLocationName(location, 5);
			for (Address tmp : gpsdaten) {
				if (tmp.hasLatitude()) {
					lat = tmp.getLatitude();
				}
				if (tmp.hasLongitude()) {
					lon = tmp.getLongitude();
				}
			}
		} catch (IllegalArgumentException iae) {
			Log.e("Error", "Could not retrieve geodata for adress");
			Toast error = Toast.makeText(this, R.string.error_adress, 3);
			error.show();
			throw new Exception();
		} catch (IOException ioe) {
			Log.e("Error", "Geocoder service not available");
			ioe.printStackTrace();
			Toast error = Toast.makeText(this, R.string.error_service, 3);
			error.show();
			throw new Exception();
		}
		return new double[] { lat, lon };
	}
}